package com.gin.kotlin.no_gay_alliance.activity

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.adapter.community.ForumSearchResultAdapter
import com.gin.kotlin.no_gay_alliance.argument.ForumSearchArgument
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingActivity
import com.gin.kotlin.no_gay_alliance.base.InputMethodUtils
import com.gin.kotlin.no_gay_alliance.base.RecyclerViewScrollListener
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.databinding.ActivityForumSearchBinding
import com.gin.kotlin.no_gay_alliance.model.ForumSearchResultModel
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.ForumSearchProvider

class ForumSearchActivity : AbstractBindingActivity<ActivityForumSearchBinding>(), TextView.OnEditorActionListener, RCallback<List<ForumSearchResultModel>, ForumSearchArgument> {
    private lateinit var adapter: ForumSearchResultAdapter
    private var page: Int = 1
    private var hasNext = true

    override fun onCreate() {
        this.page = 1
        val b = this.b ?: return

        b.swipeRefreshLayout.setOnRefreshListener { newSearch(true) }

        b.recyclerView.addOnScrollListener(RecyclerViewScrollListener(scrollToBottomListener = object : RecyclerViewScrollListener.ScrollToBottomListener {
            override fun onScrollToBottom() {
                if (hasNext) {
                    page++
                    toast("正在加载...")
                    request(true)
                }else{
                    toast("没有更多了...")
                }
            }
        }))

        this.adapter = ForumSearchResultAdapter(this, handler!!)
        b.recyclerView.adapter = adapter
        b.tvWarning.visibility = View.GONE

        b.etKeyword.setOnEditorActionListener(this)
        b.etKeyword.requestFocus()
        b.etKeyword.selectAll()
        uiDelayed(200) { InputMethodUtils.show(b.etKeyword) }
    }

    override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, menuInflater)
        // 搜索
        menuInflater.inflate(R.menu.search, menu)
    }

    override fun onContextItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.mi_search) {
            newSearch()
        }

        return super.onContextItemSelected(item)
    }

    override fun handleIntent(intent: Intent) {
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        // 当按下软键盘搜索键时，执行搜索
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            newSearch()
            return true
        }

        return false
    }

    private fun newSearch(ignoreCache: Boolean = false){
        hasNext = true
        adapter.clear()
        page = 1
        request(ignoreCache)
    }

    private fun request(ignoreCache: Boolean = false) {
        val b = this.b ?: return
        val text = b.etKeyword.text.toString()
        if (text.isEmpty()) {
            toast("关键字不能为空")
            return
        }
        Log.i(TAG, "执行搜索: $text")
        b.swipeRefreshLayout.isRefreshing = true
        ForumSearchProvider.getInstance().enqueue(ForumSearchArgument(text, this.page), ignoreCache = ignoreCache, callback = this)
    }

    companion object {
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, ForumSearchActivity::class.java)
            context.startActivity(starter)
        }
    }

    override fun onSuccess(data: List<ForumSearchResultModel>, ignoreCache: Boolean) {
        val b = this.b ?: return
        b.swipeRefreshLayout.isRefreshing = false
        this.adapter.pushData(data)
        uiDelayed(200) { InputMethodUtils.hide(b.etKeyword) }

    }

    override fun onError(errorMessage: String) {
        val b = this.b ?: return
        b.swipeRefreshLayout.isRefreshing = false
        hasNext = false
        toastLong(errorMessage)
    }
}